package com.authorization.common.utils;

import com.authorization.client.client.util.secret.SM2;
import com.authorization.client.client.util.secret.Util;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.math.ec.ECPoint;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 李晓雷
 * @Date 2020/5/6 18:27
 * @Version 1.0
 */
public class Sm2Util {

    /**
     * 生成密钥对
     * @return
     */
    public static Map<String, Object> createKey() {
        Map<String, Object> keyMap = new HashMap<>();
        SM2 sm2 = SM2.Instance();
        AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.generateKeyPair();
        ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) key.getPrivate();
        ECPublicKeyParameters ecpub = (ECPublicKeyParameters) key.getPublic();
        BigInteger privateKey = ecpriv.getD();
        ECPoint publicKey = ecpub.getQ();
        //TODO 公钥和私钥互换，已经设计成私钥加密 公钥解密 （实际是公钥加密 私钥解密）
        keyMap.put("privateKey", Util.byteToHex(publicKey.getEncoded()));
        keyMap.put("publicKey", Util.byteToHex(privateKey.toByteArray()));
        return keyMap;
    }
}
